/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.*;
import java.net.*;
import java.util.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

import org.codehaus.bloglines.*;
import org.codehaus.bloglines.exceptions.*;
import com.sun.syndication.feed.synd.*;

public class BloglinesFinder extends AbstractSearchWithLogin implements RSSCollectionFinder {

  public BloglinesFinder(String username,String password) {
    super(username,password);
  }

  public BloglinesFinder() {
    super();
  }

	private void getSubscriptions(String parent, 
                                Outline subscription, 
                                RSSCollection res) {

		if (subscription.isFeed()) {
      try {
        SyndFeed items = bloglines.getItems(subscription, false, null);
        res.addFeed(items);
        p.update("Found " + items.getTitle(),0);
      } catch (Exception e) {}
		} else {
			Outline[] children = subscription.getChildren();
			for (int i = 0; i < children.length; i++) {
				getSubscriptions(parent + " > " + subscription.getTitle(), 
                         children[i],
                         res);
			}
		}
	}

  private Bloglines bloglines = new Bloglines();
  private Progress p;

  protected RSSCollection getCollectionRest(Progress p) throws Exception {
    this.p = p;
    bloglines.setCredentials(username,password);
    Outline subs = bloglines.listSubscriptions();
    RSSCollection res = new RSSCollection();
    getSubscriptions("",subs,res);
    return res;
  }

  public String name() {
    return "Bloglines";
  }
  
  public static void main(String[] args) throws Exception {
    System.out.println(new BloglinesFinder(args[0],args[1]).getCollection(Progress.DEFAULT));
  }
}